package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 1.获取到key，用作模糊查询
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper);

        return new PageUtils(page);
    }

    /**
     * 修改品牌信息，并保证其余表冗余字段与其一致
     *
     * @param brand
     */
    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段保持一致
        this.updateById(brand);
        // 如果品牌名不为空
        if (!StringUtils.isEmpty(brand.getName())) {
            // 同步关联表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());

            // TODO 更新其他冗余信息
        }
    }


    /**
     * 根据传入品牌id获取所有品牌信息
     *
     * @param brandIds
     * @return
     */
    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        List<BrandEntity> brand_id = baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        return brand_id;
    }


}